package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.Clazz;
import com.itheima.entity.ClazzQueryParam;
import com.itheima.entity.PageBean;
import com.itheima.entity.Student;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;
    @Override
    public PageBean page(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        List<Clazz> list = clazzMapper.list(clazzQueryParam);
        Page<Clazz> page = (Page<Clazz>) list;
        return new PageBean(page.getTotal(), page.getResult());
    }

    @Override
    public void save(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.save(clazz);
    }

    @Override
    public Clazz getInfo(Integer id) {
        Clazz clazz = clazzMapper.getInfo(id);
        return clazz;
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public void deleteById(Integer id) {
        Integer count = studentMapper.countByClazzId(id);
        if (count > 0){
            throw new BusinessException("当前班级下有学生，不能删除");
        }
        clazzMapper.deleteById(id);
    }

    @Override
    public List<Clazz> list() {

        List<Clazz> list = clazzMapper.list(null);
        return list;
    }
}
